/*
 * Copyright (c) 2021-2031, 河北计全科技有限公司 (https://www.jeequan.com & jeequan@126.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.rzcf.blink.pay.trigger.http;

import cn.hutool.core.bean.BeanUtil;
import com.rzcf.blink.pay.api.http.UnifiedOrderApi;
import com.rzcf.blink.pay.api.model.UnifiedOrderReqDTO;
import com.rzcf.blink.pay.api.model.UnifiedOrderRespDTO;
import com.rzcf.blink.pay.domain.adapter.PayOrderAdapter;
import com.rzcf.blink.pay.domain.enums.OrderPayStatusEnum;
import com.rzcf.blink.pay.domain.model.valobj.UnifiedOrderRS;
import com.rzcf.blink.pay.domain.model.valobj.UnifiedOrderReqVO;
import com.rzcf.blink.pay.domain.model.valobj.UnifiedOrderRespVO;
import com.rzcf.blink.pay.types.common.CS;
import com.rzcf.blink.pay.types.model.ApiRes;
import com.rzcf.blink.pay.types.utils.JeepayKit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RestController;
import top.tangyh.basic.base.R;
import top.tangyh.basic.exception.BizException;

/**
 * 统一下单 controller
 *
 * @author dongsufeng
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class UnifiedOrderController extends ApiController implements UnifiedOrderApi {

    private final PayOrderAdapter payOrderAdapter;

    /**
     * 统一下单接口
     **/
    @Override
    public R<UnifiedOrderRespDTO> unifiedOrder(UnifiedOrderReqDTO reqDTO) {

        UnifiedOrderReqDTO rq = getRQByWithMchSign(reqDTO);
        R<UnifiedOrderRespVO> r = payOrderAdapter.unifiedOrder(BeanUtil.copyProperties(reqDTO, UnifiedOrderReqVO.class));
        return r.getIsSuccess() ? R.success(BeanUtil.copyProperties(r.getData(), UnifiedOrderRespDTO.class)) : R.fail(r.getMsg());

        //获取参数 & 验签

        UnifiedOrderReqDTO bizRQ = buildBizRQ(rq);

        //实现子类的res
        ApiRes apiRes = unifiedOrder(bizRQ.getWayCode(), bizRQ);
        if (apiRes.getData() == null) {
            return apiRes;
        }

        UnifiedOrderRS bizRes = (UnifiedOrderRS) apiRes.getData();

        //聚合接口，返回的参数
        UnifiedOrderRS res = new UnifiedOrderRS();
        BeanUtils.copyProperties(bizRes, res);

        //只有 订单生成（QR_CASHIER） || 支付中 || 支付成功返回该数据
        if (bizRes.getOrderState() != null && (bizRes.getOrderState() == OrderPayStatusEnum.STATE_INIT.getCode().intValue() ||
                bizRes.getOrderState() == OrderPayStatusEnum.STATE_ING.getCode().intValue() ||
                bizRes.getOrderState() == OrderPayStatusEnum.STATE_SUCCESS.getCode().intValue())) {
            res.setPayDataType(bizRes.buildPayDataType());
            res.setPayData(bizRes.buildPayData());
        }
        return ApiRes.okWithSign(res, configContextQueryService.queryMchApp(rq.getMchNo(), rq.getAppId()).getAppSecret());
    }


    private UnifiedOrderReqDTO buildBizRQ(UnifiedOrderReqDTO rq) {

        //支付方式  比如： ali_bar
        String wayCode = rq.getWayCode();

        //jsapi 收银台聚合支付场景 (不校验是否存在payWayCode)
        if (CS.PAY_WAY_CODE.QR_CASHIER.equals(wayCode)) {
            return rq.buildBizRQ();
        }

        //如果是自动分类条码
        if (CS.PAY_WAY_CODE.AUTO_BAR.equals(wayCode)) {

            AutoBarOrderRQ bizRQ = (AutoBarOrderRQ) rq.buildBizRQ();
            wayCode = JeepayKit.getPayWayCodeByBarCode(bizRQ.getAuthCode());
            rq.setWayCode(wayCode.trim());
        }

        if (payWayService.count(PayWay.gw().eq(PayWay::getWayCode, wayCode)) <= 0) {
            throw new BizException("不支持的支付方式");
        }

        //转换为 bizRQ
        return rq.buildBizRQ();
    }


}
